package com.polaris.live.dialog

import android.content.Context
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.ForegroundColorSpan
import android.text.style.ImageSpan
import android.text.style.StrikethroughSpan
import android.view.View
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.ColorUtils
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.CenterPopupView
import com.polaris.live.R
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.DialogPurchaseConfirmationBinding
import com.polaris.live.net.userService
import com.polaris.live.popup.CommodityPopup
import com.polaris.live.popup.DiscountPopup
import com.polaris.live.resp.back_resp.UserBackpackConsumableResp
import com.polaris.live.resp.back_resp.UserBackpackToolListResp
import com.polaris.live.resp.bean.ShopConfirmationBean
import com.polaris.live.translation.R.string
import com.polaris.live.utils.image.ImageUtils
import org.json.JSONObject

/**
 * 购买东西二次确认弹窗
 *
 * @author Created by 半仙 on 2024/10/10/010 11:33
 */
class PurchaseConfirmationDialog(
    context: Context,
    private val mViewModel: BaseViewModel,
    private val shopBean: ShopConfirmationBean,
    private val onSureCallback: (discountBackpackId: Long?, voucherBackpackId: Long?) -> Unit,
) : CenterPopupView(context) {

    private lateinit var mBinding: DialogPurchaseConfirmationBinding

    private var dataDiscount: UserBackpackConsumableResp? = null //折扣卡
    private var dataVoucher: UserBackpackConsumableResp? = null //代金券
    private var mUserBackpackToolListResp: UserBackpackToolListResp? = null //卡缓存

    override fun getImplLayoutId(): Int {
        return R.layout.dialog_purchase_confirmation
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = DialogPurchaseConfirmationBinding.bind(popupImplView)
        getCardLists { response ->
            response.discountCard?.firstOrNull()?.let { discount ->
                dataDiscount = discount
                mBinding.discountImg.apply {
                    visibility = View.VISIBLE
                    Glide.with(context).load(ImageUtils.imgPath(discount.displayUrl)).into(this)
                }
                mBinding.dressDiscountCouponTv.text = discount.name
                setTips()
            }
            if (shopBean.moneyType != CommodityPopup.TYPE_GAME_COIN) {
                response.voucher?.firstOrNull()?.let { voucher ->
                    dataVoucher = voucher
                    mBinding.voucherImg.apply {
                        visibility = View.VISIBLE
                        Glide.with(context).load(ImageUtils.imgPath(voucher.displayUrl)).into(this)
                    }
                    mBinding.dressUpVoucherTv.text = voucher.name
                    setTips()
                }

            }
        }
        Glide.with(context)
            .load(ImageUtils.imgPath(shopBean.displayUrl))
            .into(mBinding.commodityImg)

        if (shopBean.otherNickName?.isNotEmpty() == true) {
            mBinding.titleTv.text = StringUtils.getString(string.send_confirmation)
            mBinding.wear.text = StringUtils.getString(string.me_send)
        } else {
            mBinding.titleTv.text = StringUtils.getString(string.purchase_confirmation)
            mBinding.wear.text = StringUtils.getString(string.buy)
        }
        setTips()

        if (shopBean.moneyType == CommodityPopup.TYPE_GAME_COIN) {
            mBinding.voucherTitleLl.visibility = View.GONE
            mBinding.dressUpVoucherCl.visibility = View.GONE
        } else {
            mBinding.voucherTitleLl.visibility = View.VISIBLE
            mBinding.dressUpVoucherCl.visibility = View.VISIBLE
        }
        mBinding.nameTv.text =
            "${shopBean.shoppName}*${shopBean.day}${StringUtils.getString(string.one_days)}"
        initListener()
    }

    private fun initListener() {
        mBinding.look.setOnSingleClickListener {
            dismiss()
        }
        mBinding.wear.setOnSingleClickListener {
            onSureCallback.invoke(dataDiscount?.backpackId, dataVoucher?.backpackId)
            dismiss()
        }
        mBinding.dressDiscountCouponCl.setOnSingleClickListener {
            getCardListsByType(DiscountPopup.DISCOUNT_CARD) { lists ->
                DiscountPopup.show(
                    context,
                    StringUtils.getString(string.dress_discount_coupon),
                    lists
                ) {
                    dataDiscount = it
                    if (dataDiscount != null) {
                        mBinding.discountImg.visibility = View.VISIBLE
                        dataDiscount?.let { da ->
                            Glide.with(context).load(ImageUtils.imgPath(da.displayUrl)).into(mBinding.discountImg)
                            mBinding.dressDiscountCouponTv.text = da.name
                        }
                    } else {
                        mBinding.discountImg.visibility = View.GONE
                        mBinding.dressDiscountCouponTv.text = StringUtils.getString(string.not_using_discounts)
                    }
                    setTips()
                }
            }

        }
        mBinding.dressUpVoucherCl.setOnSingleClickListener {
            getCardListsByType(DiscountPopup.VOUCHER) { lists ->
                DiscountPopup.show(
                    context,
                    StringUtils.getString(string.dress_up_voucher),
                    lists
                ) {
                    dataVoucher = it
                    if (dataVoucher != null) {
                        mBinding.voucherImg.visibility = View.VISIBLE
                        dataVoucher?.let { da ->
                            Glide.with(context).load(ImageUtils.imgPath(da.displayUrl)).into(mBinding.voucherImg)
                            mBinding.dressUpVoucherTv.text = da.name
                        }
                    } else {
                        mBinding.voucherImg.visibility = View.GONE
                        mBinding.dressUpVoucherTv.text = StringUtils.getString(string.not_using_discounts)
                    }
                    setTips()
                }
            }
        }
        mBinding.discountWhat.setOnSingleClickListener {
            ToastGravity.showGravity(string.tasks_to_receive_discount)
        }
        mBinding.voucherWhat.setOnSingleClickListener {
            ToastGravity.showGravity(string.tasks_to_receive_vouchers)
        }
    }

    /**
     * 获取数据
     */
    private fun getCardLists(back: (data: UserBackpackToolListResp) -> Unit) {
        mViewModel.requestLoading({
            userService.getConsumableListType("${DiscountPopup.DISCOUNT_CARD},${DiscountPopup.VOUCHER}")
        }, { response ->
            mUserBackpackToolListResp = response
            back(response)
        }, { error ->
            ToastGravity.showGravity(error.errorMsg)
        }
        )
    }

    /**
     * 获取数据
     */
    private fun getCardListsByType(type: Int, back: (list: List<UserBackpackConsumableResp>) -> Unit) {
        mUserBackpackToolListResp?.let { existingLists ->
            val cardList = when (type) {
                DiscountPopup.DISCOUNT_CARD -> existingLists.discountCard
                DiscountPopup.VOUCHER -> existingLists.voucher
                else -> null
            }
            if (cardList != null) {
                back(cardList)
                return
            }
        }
        getCardLists { response ->
            val cardList = when (type) {
                DiscountPopup.DISCOUNT_CARD -> response.discountCard
                DiscountPopup.VOUCHER -> response.voucher
                else -> null
            }
            cardList?.let { back(it) }
        }
    }

    private fun setTips() {
        var originalMoney: Long = shopBean.money
        dataDiscount?.let {
            if (it.ext != null) {
                val jsonObject = JSONObject(it.ext)
                val discount = jsonObject.getLong("discount")
                if (discount in 0..100) {
                    originalMoney = (originalMoney * discount / 100f).toLong()
                }
            }
        }
        dataVoucher?.let {
            if (it.ext != null) {
                val jsonObject = JSONObject(it.ext)
                val coin = jsonObject.getLong("coin")
                if (coin > 0) {
                    originalMoney -= coin
                }
            }
        }
        if (originalMoney < 0) {
            originalMoney = 0
        }
        val drawable = when (shopBean.moneyType) {
            CommodityPopup.TYPE_DIAMOND -> ContextCompat.getDrawable(context, R.drawable.diamond)
            CommodityPopup.TYPE_GAME_COIN -> ContextCompat.getDrawable(context, R.drawable.other_game_reward_game_beans)
            CommodityPopup.TYPE_GAIN_BEANS -> ContextCompat.getDrawable(context, R.drawable.anchor_ic_beans)
            else -> null
        }
        if (shopBean.otherNickName?.isNotEmpty() == true) {
            val firstContent = " $originalMoney ${shopBean.originalPrice} %XX%"
            val str = StringUtils.getString(
                string.sure_bug_this_send_other,
                firstContent,
                "${shopBean.otherNickName}"
            )
            val spannableString = SpannableString(str)
            val secondContent = shopBean.otherNickName

            val firstStart = str.indexOf(firstContent)
            val firstEnd = firstStart + firstContent.length

            val secondStart = str.indexOf(secondContent)
            val secondEnd = secondStart + secondContent.length

            val firstStart1 = firstStart + "$originalMoney".length + 2
            val firstEnd2 = firstStart1 + "${shopBean.originalPrice}".length

            val imgStart = str.indexOf("%XX%")
            val imgEnd = imgStart + 4

            spannableString.setSpan(
                ForegroundColorSpan(ColorUtils.getColor(R.color.color_ffa100)),
                firstStart,
                firstEnd,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                ForegroundColorSpan(ColorUtils.getColor(R.color.color_9b9b9b)),
                firstStart1,
                firstEnd2,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                StrikethroughSpan(),
                firstStart1,
                firstEnd2,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                AbsoluteSizeSpan(10, true),
                firstStart1,
                firstEnd2,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )

            spannableString.setSpan(
                ForegroundColorSpan(ColorUtils.getColor(R.color.color_ffa100)),
                secondStart,
                secondEnd,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )

            drawable?.let {
                drawable.setBounds(0, 0, 10.autoDp, 10.autoDp)
                val imageSpan = ImageSpan(drawable, ImageSpan.ALIGN_BASELINE)
                spannableString.setSpan(
                    imageSpan,
                    imgStart,
                    imgEnd,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                )
            }

            mBinding.tipsTv.text = spannableString
        } else {
            val firstContent = " $originalMoney ${shopBean.originalPrice} %XX%"
            val str = StringUtils.getString(string.sure_bug_this_shop, firstContent)
            val spannableString = SpannableString(str)

            val firstStart = str.indexOf(firstContent)
            val firstEnd = firstStart + firstContent.length

            val firstStart1 = firstStart + "$originalMoney".length + 2
            val firstEnd2 = firstStart1 + "${shopBean.originalPrice}".length

            val imgStart = str.indexOf("%XX%")
            val imgEnd = imgStart + 4
            spannableString.setSpan(
                ForegroundColorSpan(ColorUtils.getColor(R.color.color_ffa100)),
                firstStart,
                firstEnd,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                ForegroundColorSpan(ColorUtils.getColor(R.color.color_9b9b9b)),
                firstStart1,
                firstEnd2,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                StrikethroughSpan(),
                firstStart1,
                firstEnd2,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            spannableString.setSpan(
                AbsoluteSizeSpan(10, true),
                firstStart1,
                firstEnd2,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )

            drawable?.let {
                drawable.setBounds(0, 0, 10.autoDp, 10.autoDp)
                val imageSpan = ImageSpan(drawable, ImageSpan.ALIGN_BASELINE)
                spannableString.setSpan(
                    imageSpan,
                    imgStart,
                    imgEnd,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE
                )
            }
            mBinding.tipsTv.text = spannableString

        }

    }

    companion object {

        fun show(
            context: Context,
            mViewModel: BaseViewModel,
            shopConfirmationBean: ShopConfirmationBean,
            onSureCallback: (discountBackpackId: Long?, voucherBackpackId: Long?) -> Unit,
        ) {
            XPopup.Builder(context)
                .isDestroyOnDismiss(true)
                .asCustom(PurchaseConfirmationDialog(context, mViewModel, shopConfirmationBean, onSureCallback))
                .show()
        }
    }
}